<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 后台酒店订单管理控制器
 */
class Order_Adminhotel_module extends CI_Module {

    /**
     * 站点配置ID
     *
     * @var string
     */
    private $sid;
    private $data;
    private $period_price_array;
    private $order_status_array;
    private $pay_status_array;

    /**
     * 构造函数
     */
    function __construct()
    {
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->data = $GLOBALS['config'];

        $this->load->model('order.Orderlog_model');
        $this->load->model('order.Orderpaylog_model');
        $this->load->model('order.Ordercontacts_model');
        $this->load->model('order.Orderinfo_model');
        $this->load->model('order.Orderhotel_model');
        $this->load->model('order.Orderroom_model');
        $this->load->model('hotel.Hotel_model');
        $this->load->model('order.Ordertourist_model');
        $this->load->model('order.Orderhotelgoods_model');
        $this->load->model('member.User_model');
 
        $this->load->model('order.Ordernumberlog_model');
        
        $this->config->load('base');
        $this->order_status_array = $this->config->item('order_status');
        $this->pay_status_array = $this->config->item('pay_status');

        $this->period_price_array = array(
            $GLOBALS['config']['week_unit_price'],
            $GLOBALS['config']['mon_unit_price'],
            $GLOBALS['config']['tue_unit_price'],
            $GLOBALS['config']['wed_unit_price'],
            $GLOBALS['config']['thu_unit_price'],
            $GLOBALS['config']['fri_unit_price'],
            $GLOBALS['config']['sat_unit_price']
        );
    }

    /**
     * 酒店订单列表
     */
    public function index()
    {
        $data['index_url'] = site_url('order/adminhotel/index');

        //查询条件
        $condition['order_sn'] = addslashes($this->input->get_post('order_sn'));
        $condition['contact'] = addslashes($this->input->get_post('contact'));
        $condition['order_status'] = addslashes($this->input->get_post('order_status'));

        $condition['start'] = $this->input->get_post('start') ? $this->input->get_post('start') : '';
        $condition['end'] = $this->input->get_post('end') ? $this->input->get_post('end') : '';


        $order_info_table = $this->db->dbprefix("order_info");
        $order_hotel_table = $this->db->dbprefix("order_hotel");

        $where = "" . $order_info_table . ".order_type=1 AND " . $order_info_table . ".sid=$this->sid ";//酒店订单


        //订单流水号
        if ($condition['order_sn'])
        {
            if ($where != '') $where .= " AND ";
            $where .= "" . $order_info_table . ".order_sn like '%" . $condition['order_sn'] . "%' ";
        }

        if ($condition['order_status'])
        {
            if ($where != '') $where .= " AND ";
            $where .= "" . $order_info_table . ".order_status=" . $condition['order_status'];
        }

        //联系人
        if ($condition['contact'])
        {
            $contact_table = $this->db->dbprefix("order_contacts");
            if ($where != '') $where .= " AND ";
            $where .= " (" . $contact_table . ".name like '%" . $condition['contact'] . "%' OR " . $contact_table . ".phone_num like '%" . $condition['contact'] . "%')";
        }


        // 入住日期
        if(strtotime($condition['start']))
        {
            if ($where != '') $where .= " AND ";
            $where .= " $order_hotel_table.start_date >='{$condition['start']}' ";
        }

        // 离店日期
        if(strtotime($condition['end']))
        {
            if ($where != '') $where .= " AND ";
            $where .= " $order_hotel_table.end_date <='{$condition['end']}' ";
        }

        $page_config['perpage'] = 20;   //每页条数
        $page_config['part'] = 2;//当前页前后链接数量
        $page_config['url'] = 'order/adminhotel/index';//url
        $page_config['param'] = '?order_sn=' . $condition['order_sn'] . '&contact=' . $condition['contact'] . '&order_status=' . $condition['order_status'] ;//参数
        $page_config['seg'] = 4;//参数取 index.php之后的段数，默认为3，即index.php/control/function/18 这种形式
        $page_config['nowindex'] = $this->uri->segment($page_config['seg']) ? $this->uri->segment($page_config['seg']) : 1;//当前页
        $page_config['total'] = $this->Orderhotel_model->get_order_count($where);
        $this->load->library('mypageclass');
        $this->mypageclass->initialize($page_config);


        $order_info_fields = format_table_field(array('order_id', 'order_account','earnest_account', 'order_sn', 'order_status', 'pay_status','cat_type', 'add_time,paid_account,earnest_paid_account'), $this->db->dbprefix("order_info"));
        $contact_fields = format_table_field(array('name as contact_name', 'phone_num', 'wx_nick'), $this->db->dbprefix("order_contacts"));

        $order_hotel_fields = format_table_field(array('number', 'start_date', 'end_date'), $this->db->dbprefix("order_hotel"));

        $fields = $contact_fields . ',' . $order_hotel_fields . ',' . $order_info_fields;
        $result = $this->Orderhotel_model->get_order_list($page_config['perpage'], $page_config['nowindex'], $where, $fields);

        if ($result)
        {
            foreach ($result as $key => $item)
            {
                $order_room_table = $this->db->dbprefix("order_room");
                $hotel_room_table = $this->db->dbprefix("hotel_room");

                $rstr = array();
                $rdate = array();
                $room = $this->Orderroom_model->get_room_info_array("$order_room_table.order_id = {$item['order_id']}", "$hotel_room_table .name,$order_room_table .date ", false, false);

                if ($room)
                {
                    foreach ($room as $index => $value)
                    {
                        $rstr[$index] = $value['name'];
                        $rdate[$index] = fdate($value['date']);
                    }
                }
                $rstr = array_unique($rstr);
                $rdate = array_unique($rdate);

                $result[$key]['rstr'] = !empty($rstr) ? implode(',', $rstr) : '未安排房间';
                $result[$key]['rdate'] = !empty($rdate) ? implode(',', $rdate) : '';


                $result[$key]['past_order_status'] = (strtotime($item['end_date']) < time()) ? true : false;


                // 取消订单
                if ($item['order_status'] != 3)
                    $result[$key]['cancel_url'] = site_url('order/admin/ajax_order_status?order_id=' . $item['order_id'] . '&status=3');


/*
                if ($item['order_status'] == 4)  $result[$key]['edit_url_title'] = '安排房间';*/

                if (in_array($item['order_status'],array(1,2,4,5)))  $result[$key]['edit_url_title'] = '编辑';
                if (in_array($item['order_status'],array(3,6)))  $result[$key]['edit_url_title'] = '详情';

                $result[$key]['edit_url'] = site_url('order/adminhotel/edit?id=' . $item['order_id']);


                // 完成订单
                if ($item['order_status'] == 5 && $item['pay_status'] == 3)
                    $result[$key]['finish_url'] = site_url('order/admin/ajax_order_status?order_id=' . $item['order_id'] . '&status=6');

                // 审核订单
                if ($item['order_status'] == 1)
                    $result[$key]['check_url'] = site_url('order/admin/ajax_order_status?order_id=' . $item['order_id'] . '&status=2');


                // 支付订单
                if ($item['order_status'] == 4)
                {
                    $result[$key]['into_url'] = site_url('order/admin/ajax_order_status?order_id=' . $item['order_id'] . '&status=5');

                }



                // 支付订单
                if ($item['order_status'] == 5 && $item['paid_account'] < $item['order_account'])
                {
                    $result[$key]['pay_url'] = site_url('order/admin/ajax_pay_account?id=' . $item['order_id']);
                }

                // 删除订单
                $result[$key]['delete_url'] = site_url('order/adminhotel/delete_order?id=' . $item['order_id']);
                $result[$key]['order_status_name'] = $this->order_status_array[$item['order_status']];
                $result[$key]['pay_status_name'] = $this->pay_status_array[$item['pay_status']];

            }
        }


        $data['list'] = $result;
        $data['condition'] = $condition;
        $data['add_url'] = site_url('order/adminhotel/add');


        if($_GET['ajax']){



            $start = date('m-d',strtotime( $condition['start']));
            $end = date('m-d',strtotime( $condition['end']));
            $condition['end'] = date('Y-m-d',strtotime( $condition['end'])+60*60*24);
            $where = "" . $order_info_table . ".order_type=1 AND " . $order_info_table . ".sid=$this->sid ";//酒店订单

            if($condition['start']&&$condition['end'])
            {
                if ($where != '') $where .= " AND ";
                $where .= " ($order_hotel_table.start_date >='{$condition['start']}' AND  $order_hotel_table.end_date <= '{$condition['end']}' )";
            }



            $order_info_fields = format_table_field(array('order_id', 'order_note','order_account','earnest_account', 'order_sn', 'order_status', 'pay_status','cat_type', 'add_time,paid_account,earnest_paid_account'), $this->db->dbprefix("order_info"));
            $contact_fields = format_table_field(array('name as contact_name', 'phone_num', 'wx_nick'), $this->db->dbprefix("order_contacts"));

            $order_hotel_fields = format_table_field(array('number', 'start_date', 'end_date'), $this->db->dbprefix("order_hotel"));

            $fields = $contact_fields . ',' . $order_hotel_fields . ',' . $order_info_fields;
            $count = $this->Orderhotel_model->get_order_count($where);

            $result = $this->Orderhotel_model->get_order_list($count, 1, $where, $fields);


            if ($result)
            {
                foreach ($result as $key => $item)
                {
                    $order_room_table = $this->db->dbprefix("order_room");
                    $hotel_room_table = $this->db->dbprefix("hotel_room");

                    $rstr = array();
                    $rdate = array();
                    $room = $this->Orderroom_model->get_room_info_array("$order_room_table.order_id = {$item['order_id']}", "$hotel_room_table .name,$hotel_room_table .id,$order_room_table .date ", false, false);

                /*    if ($room)
                    {
                        foreach ($room as $index => $value)
                        {
                            $res = $this->Hotel_model->_get_number_row(array('id'=>$value['id']),'note');

                            $room[$index]['note']  =$res['note'];
                        }
                    }*/

//                    $result[$key]['room_list'] = $room ;

                    if ($room)
                    {
                        foreach ($room as $index => $value)
                        {
                            $rstr[$index] = $value['name'];
                            $rdate[$index] = fdate($value['date']);
                        }
                    }
//                    print_r($rstr);

                    $rstr = array_unique($rstr);
                    $rdate = array_unique($rdate);

                    $result[$key]['rnstr'] = !empty($rstr) ? implode("\n", $rstr) : '未安排房间';
                    $result[$key]['rstr'] = !empty($rstr) ? implode(',', $rstr) : '未安排房间';
                    $result[$key]['rdate'] = !empty($rdate) ? implode(',', $rdate) : '';


                    $result[$key]['past_order_status'] = (strtotime($item['end_date']) < time()) ? true : false;

                    $result[$key]['order_status_name'] = $this->order_status_array[$item['order_status']];
                    $result[$key]['pay_status_name'] = $this->pay_status_array[$item['pay_status']];

                }
            }





            define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

            if (PHP_SAPI == 'cli')
                die('This example should only be run from a Web Browser');

            /** Include PHPExcel */
            require_once (APPPATH.'libraries/Classes/PHPExcel.php');


            $objPHPExcel = new PHPExcel();

            $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                ->setLastModifiedBy("Maarten Balliauw")
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");


            /*$objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A2', '序号')
                ->setCellValue('B2', '房间号')
                ->setCellValue('C2', '房间备注')
                ->setCellValue('D2', '订单备注')
                ->setCellValue('E2', '入住姓名')
                ->setCellValue('F2', '入住手机号')
            ;

            if(count($result)){
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A1', $start.'到'.$end.'  房间库存');
                $index = 3;
                $i = 0;
                foreach($result as $key=>$val){

                    if ($val['room_list'])
                    {
                        foreach ($val['room_list'] as  $item)
                        {
                            $objPHPExcel->setActiveSheetIndex(0)
                                ->setCellValue('A' . $index, $i + 1)
                                ->setCellValueExplicit('B' . $index, $item['name'], PHPExcel_Cell_DataType::TYPE_STRING)
                                ->setCellValue('C' . $index, $item['note'])
                                ->setCellValue('D' . $index, $val['order_note'])
                                ->setCellValue('E' . $index, $val['contact_name'])
                                ->setCellValue('F' . $index, $val['phone_num']);
                            $index++;
                            $i++;
                        }
                    }
                     else
                    {
                        $objPHPExcel->setActiveSheetIndex(0)
                            ->setCellValue('A' . $index, $i + 1)
                            ->setCellValueExplicit('B' . $index, '未安排房间', PHPExcel_Cell_DataType::TYPE_STRING)
                            ->setCellValue('C' . $index, '房间备注')
                            ->setCellValue('D' . $index, $val['order_note'])
                            ->setCellValue('E' . $index, $val['contact_name'])
                            ->setCellValue('F' . $index, $val['phone_num']);
                    }

                    $index++;
                    $i++;

                }

            }*/


            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A3', '序号')
                ->setCellValue('B3', '房间号')
                ->setCellValue('C3', '人数')
                ->setCellValue('D3', '联系人')
                ->setCellValue('E3', '手机号')
                ->setCellValue('F3', '入住日期')
                ->setCellValue('G3', '离店日期')
                ->setCellValue('H3', '订单状态')
//                ->setCellValue('I2', '下单时间')
            ;

            if(count($result)){
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A1', $start.'到'.$end.'  订单入住情况');


                foreach($result as $key=>$val){
                    $index = $key+4;

                    $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A' . $index, $key + 1)
                        ->setCellValueExplicit('B' . $index, "{$val['rnstr']}", PHPExcel_Cell_DataType::TYPE_STRING)
                        ->setCellValue('C' . $index, $val['number'].'人')
                        ->setCellValue('D' . $index, $val['contact_name'])
                        ->setCellValue('E' . $index, $val['phone_num'])
                        ->setCellValue('F' . $index, $val['start_date'])
                        ->setCellValue('G' . $index, $val['end_date'])
                        ->setCellValue('H' . $index, $val['order_status_name'].'/'.$val['pay_status_name']);
//                        ->setCellValue('I' . $index, $val['add_time']);
                }

                $objPHPExcel->getActiveSheet()->getStyle('B'.$index)->getAlignment()->setWrapText(true);
                $objPHPExcel->getActiveSheet()->getStyle('H'.$index)->getAlignment()->setWrapText(true);
            }


            $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
            $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(6);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(8);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
            $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
//            $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(18);

            $objPHPExcel->getActiveSheet()->mergeCells('A1:H1');
            $objPHPExcel->getActiveSheet()->setTitle('订单入住情况');


            $objPHPExcel->setActiveSheetIndex(0);


            $filename =  $start.'__'.$end.'_dingdanruzhu-.xls';
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.$filename.'"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');

            header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
            header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header ('Pragma: public'); // HTTP/1.0

            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;






        }

        $this->load->view('admin/hotel/list', $data);
    }



    /**
     * 后台首页订单统计
     */
    public function static_list()
    {

        $order_info_table = $this->db->dbprefix("order_info");
        $order_hotel_table = $this->db->dbprefix("order_hotel");

        $where = "" . $order_info_table . ".order_type=1 AND " . $order_info_table . ".sid=$this->sid "; //酒店订单

            //待审核
        $ncheck_sql =  $where." and ".$order_info_table . ".order_status = 1 ";


        $nincom_sql =  $where." and ( $order_hotel_table.start_date <= '".date('Y-m-d')."' or $order_hotel_table.end_date <= '".date('Y-m-d')."'  ) and (".$order_info_table . ".order_status = 4 or ".$order_info_table . ".order_status = 2) ";

            //已入住
        $hincom_sql =  $where." and '".date('Y-m-d')."' >= $order_hotel_table.start_date and '".date('Y-m-d')."' <= $order_hotel_table.end_date and ".$order_info_table . ".order_status = 5 ";

            //已完成
        $finish_sql =  $where." and $order_hotel_table.end_date = '".date('Y-m-d')."' and ".$order_info_table . ".order_status = 6 ";


        $order_info_fields = format_table_field(array('order_id', 'order_account','earnest_account', 'order_sn', 'order_status', 'pay_status','cat_type', 'add_time,paid_account,earnest_paid_account'), $this->db->dbprefix("order_info"));
        $contact_fields = format_table_field(array('name as contact_name', 'phone_num', 'wx_nick'), $this->db->dbprefix("order_contacts"));

        $order_hotel_fields = format_table_field(array('number', 'start_date', 'end_date'), $this->db->dbprefix("order_hotel"));

        $fields = $contact_fields . ',' . $order_hotel_fields . ',' . $order_info_fields;


        $wait_list = $this->Orderhotel_model->get_order_list(200, 1, $ncheck_sql, $fields);
        $not_in_list = $this->Orderhotel_model->get_order_list(200, 1, $nincom_sql, $fields);
        $in_list = $this->Orderhotel_model->get_order_list(200, 1, $hincom_sql, $fields);
        $comp_list = $this->Orderhotel_model->get_order_list(200, 1, $finish_sql, $fields);

        $wait_list = $this->formate_result_list($wait_list);

        $not_in_list = $this->formate_result_list($not_in_list);
        $in_list = $this->formate_result_list($in_list);

        $comp_list = $this->formate_result_list($comp_list);


        $data['comp_list'] = $comp_list ;
        $data['wait_list'] = $wait_list ;
        $data['in_list'] = $in_list ;
        $data['not_in_list'] = $not_in_list ;

        $this->load->view('admin/hotel/static_list',$data);
    }


    public function formate_result_list($result)
    {


        if($result)
        {
            foreach ($result as $key => $item)
            {
                $order_room_table = $this->db->dbprefix("order_room");
                $hotel_room_table = $this->db->dbprefix("hotel_room");

                $rstr = array();
                $rdate = array();
                $room = $this->Orderroom_model->get_room_info_array("$order_room_table.order_id = {$item['order_id']}", "$hotel_room_table .name,$order_room_table .date ", false, false);

                if ($room)
                {
                    foreach ($room as $index => $value)
                    {
                        $rstr[$index] = $value['name'];
                        $rdate[$index] = fdate($value['date']);
                    }
                }
                $rstr = array_unique($rstr);
                $rdate = array_unique($rdate);

                $result[$key]['rstr'] = !empty($rstr) ? implode(',', $rstr) : '未安排房间';
                $result[$key]['rdate'] = !empty($rdate) ? implode(',', $rdate) : '';


                $result[$key]['past_order_status'] = (strtotime($item['end_date']) < time()) ? true : false;


                // 取消订单
                if ($item['order_status'] != 3)
                    $result[$key]['cancel_url'] = site_url('order/admin/ajax_order_status?order_id=' . $item['order_id'] . '&status=3');



                if (in_array($item['order_status'],array(1,2,4,5)))  $result[$key]['edit_url_title'] = '编辑';
                if (in_array($item['order_status'],array(3,6)))  $result[$key]['edit_url_title'] = '详情';

                $result[$key]['edit_url'] = site_url('order/adminhotel/edit?id=' . $item['order_id'].'&is_index=1');



                // 支付订单
                if ($item['order_status'] == 5 && $item['paid_account'] < $item['order_account'])
                {
                    $result[$key]['pay_url'] = site_url('order/admin/ajax_pay_account?id=' . $item['order_id']);
                }

                // 删除订单
                $result[$key]['order_status_name'] = $this->order_status_array[$item['order_status']];
                $result[$key]['pay_status_name'] = $this->pay_status_array[$item['pay_status']];

            }
        }
        return $result;
    }




    /**
     * 一口价模式-订单添加
     */

    public function add()
    {
        $start = $this->input->get_post('start') ? ($this->input->get_post('start')) : date('Y-m-d');
        $end = $this->input->get_post('end') ? ($this->input->get_post('end')) : date('Y-m-d', strtotime('+1 day'));

        $condition = array('status' => 1, 'sid' => $this->sid);
        $this->data['list'] = $this->Hotel_model->get_number_list($condition);


        $this->data['room_list'] = $this->Hotel_model->get_number_array(array('sid' => $this->sid));


        $locked_data = $this->Orderroom_model->get_locked_room_list($start, $end);
        $this->data['lock_room'] = $locked_data['ids'];
        $this->data['lock_key_date'] = $locked_data['dates'];

        $this->data['goods_list'] = $this->Hotel_model->get_extend_product_list("sid = " . $this->sid." and type = 0");

        // 酒水管理

        $this->data['drinks_list']  = $this->Hotel_model->get_extend_product_list("sid = " . $this->sid." and type = 1");

        $this->data['member_list']  = $this->User_model->get_member_list("sid = " . $this->sid,100,1);
        $this->data['start'] = $start;
        $this->data['days'] = (strtotime($end)-strtotime($start))/24/60/60;
        $this->data['end'] = $end;
        $this->data['form_url'] = site_url('order/adminhotel/order_save');
        $this->data['list_url'] = site_url('order/adminhotel/index');
        $this->data['index_url'] = site_url('order/adminhotel/index');




        // 混合价格模式
        if (intval($this->data['sell_model']) == 2)
        {


                $period_unit_price = 0 ;
                $date_range = fomate_range_date($start, $end);
                if($date_range)
                {
                    foreach ($date_range as $index => $item)
                    {
                        $period_unit_price += $this->period_price_array[date('w',strtotime($item))];
                    }
                }
                $this->data['period_unit_price'] = $period_unit_price; // 周期单价


            $this->data['form_url'] = site_url('order/adminhotel/order_mix_save');
            $this->load->view('admin/hotel/mix/add', $this->data);
        }
        elseif (intval($this->data['sell_model']) == 1) // 测试独立房间价格模式
        {
            $this->data['form_url'] = site_url('order/adminhotel/order_independ_save');
//            print_r( $this->data['room_list']);


//            if(TADMIN)
//            {
            $this->load->view('admin/hotel/independ/add', $this->data);
//            }else
//            {
//                $this->load->view('admin/hotel/tadmin/add', $this->data);
//            }
        }
        else
        {
            /* if(TADMIN)
             {
                 $this->load->view('admin/hotel/test/add', $this->data);
             }else
             {
                 $this->load->view('admin/hotel/general/add', $this->data);
             }*/
            $this->load->view('admin/hotel/normal/add', $this->data);
        }
    }


    /**
     * 一口价模式-订单添加保存
     */
    public function order_save()
    {
        $arg_post = $this->input->post();


        //订单信息
        $order_data = array(
            'sid' => $this->sid,
            'order_sn' => $this->Orderinfo_model->set_order_sn(),
            'order_type' => 1,//酒店订单
            'cat_type' => 1,  //门市订单
            'order_account' => $arg_post['order_account'],
            'room_account' => $arg_post['room_account'],
            'earnest_account' => $arg_post['order_account']/3,
            'order_status' => 4, // 管理员下单已确认状态
            'pay_status' => 1,   // 未支付
            'add_time' => date('Y-m-d H:i:s', now()),
            'order_note' => $arg_post['order_note'],
            'user_id' => $arg_post['user_id'],//用户ID
            'admin_user_id' => $this->session->userdata('admin_user_id'),//管理员ID
        );


        $order_id = $order_return_status = $this->Orderinfo_model->add_row($order_data);
        if ($order_id)
        {
            //添加联系人
            $contact_data = array(
                'order_id' => $order_id,
                'name' => $arg_post['contact_name'],
                'phone_num' => $arg_post['contact_phone_num'],
                'wx_nick' => $arg_post['wx_nick'],
            );
            $contact_return_status = $this->Ordercontacts_model->add_row($contact_data);


            // 添加酒店订单信息

            $hotel_data = array(
                'sid' => $this->sid,
                'order_id' => $order_id,
                'start_date' => $arg_post['start_date'],
                'end_date' => $arg_post['end_date'],
                'number' => $arg_post['male_number'] + $arg_post['woman_number']+ $arg_post['child_number'],
                'male_number' => $arg_post['male_number'],
                'woman_number' => $arg_post['woman_number'],
                'child_number' => $arg_post['child_number'],
                'room_account' => $arg_post['room_account']
            );

            $hor_check = $this->Orderhotel_model->add_row($hotel_data);

            // 添加房间
            if (!empty($arg_post['room_id']) && is_array($arg_post['room_id']))
            {

                $this->Orderroom_model->delete_row(array('order_id' => $order_id));
                $insert_data = array();
                $range = fomate_range_date($arg_post['start_date'], $arg_post['end_date']);


                foreach ($arg_post['room_id'] as $key => $item)
                {
                    foreach ($range as $index => $value)
                    {
                        $insert_data[$key][$index]['sid'] = $this->sid;
                        $insert_data[$key][$index]['room_id'] = $item;
                        $insert_data[$key][$index]['order_id'] = $order_id;
                        $insert_data[$key][$index]['date'] = $value;
                    }

                }

                foreach ($insert_data as $key => $value)
                {
                    $this->Orderroom_model->add_batch($value);
                }

            }

            // 添加商品
            $go_batch_data = array();
            $order_goods_status = true;
            if ($arg_post['gids'] && $arg_post['gnums'])
            {
                foreach ($arg_post['gids'] as $index => $gid)
                {
                    $go_batch_data[$index] = array(
                        'sid' => $this->sid,
                        'order_id' => $order_id,
                        'good_id' => $gid,
                        'number' => $arg_post['gnums'][$index],
                    );
                }
            }

            if(!empty($go_batch_data))
            {
                $order_goods_status = $this->Orderhotelgoods_model->add_batch($go_batch_data);
            }


            //保存人数日志信息
            $log_data = array(
                'sid' => $this->sid,
                'order_id' => $order_id,
                'number' => $arg_post['male_number'] + $arg_post['woman_number'] + $arg_post['child_number'],
                'date' => $arg_post['start_date'],
                'add_time' => date('Y-m-d'),
                'action_user' => $this->session->userdata('admin_user_name')
            );
            $number_log = $this->Ordernumberlog_model->add_row($log_data);


            if ($contact_return_status && $hor_check && $order_goods_status)
            {
                $this->User_model->_send_sms($contact_data['phone_num'],'SMS_10820180',array('number'=>$hotel_data['number']));
                $this->success('订单生成成功!', site_url('order/adminhotel/index'), true);
            }
            else
            {
                $this->error('订单生成失败!', site_url('order/adminhotel/add'), true);
            }
        }
        else
        {
            $this->error('订单生成失败!', site_url('order/adminhotel/add'), true);
        }
    }


    /**
     * 混合模式-订单添加保存
     */
    public function order_mix_save()
    {
        $arg_post = $this->input->post();


        //订单信息
        $order_data = array(
            'sid' => $this->sid,
            'order_sn' => $this->Orderinfo_model->set_order_sn(),
            'order_type' => 1,//酒店订单
            'cat_type' => 1,  //门市订单
            'order_account' => $arg_post['order_account'],
            'room_account' => $arg_post['room_account'],
            'earnest_account' => $arg_post['order_account']/3,
            'order_status' => 4, // 管理员下单已确认状态
            'pay_status' => 1,   // 未支付
            'add_time' => date('Y-m-d H:i:s', now()),
            'order_note' => $arg_post['order_note'],
            'user_id' => $arg_post['user_id'],//用户ID
            'admin_user_id' => $this->session->userdata('admin_user_id'),//管理员ID
        );


        $order_id = $order_return_status = $this->Orderinfo_model->add_row($order_data);
        if ($order_id)
        {
            //添加联系人
            $contact_data = array(
                'order_id' => $order_id,
                'name' => $arg_post['contact_name'],
                'phone_num' => $arg_post['contact_phone_num'],
                'wx_nick' => $arg_post['wx_nick'],
            );
            $contact_return_status = $this->Ordercontacts_model->add_row($contact_data);


            // 添加酒店订单信息

            $hotel_data = array(
                'sid' => $this->sid,
                'order_id' => $order_id,
                'start_date' => $arg_post['start_date'],
                'end_date' => $arg_post['end_date'],
                'number' => $arg_post['male_number'] + $arg_post['woman_number']+ $arg_post['child_number'],
                'male_number' => $arg_post['male_number'],
                'woman_number' => $arg_post['woman_number'],
                'child_number' => $arg_post['child_number'],
                'room_account' => $arg_post['room_account']
            );

            $hor_check = $this->Orderhotel_model->add_row($hotel_data);

            // 添加房间
            if (!empty($arg_post['room_id']) && is_array($arg_post['room_id']))
            {

                $this->Orderroom_model->delete_row(array('order_id' => $order_id));
                $insert_data = array();
                $range = fomate_range_date($arg_post['start_date'], $arg_post['end_date']);


                foreach ($arg_post['room_id'] as $key => $item)
                {
                    foreach ($range as $index => $value)
                    {
                        $insert_data[$key][$index]['sid'] = $this->sid;
                        $insert_data[$key][$index]['room_id'] = $item;
                        $insert_data[$key][$index]['order_id'] = $order_id;
                        $insert_data[$key][$index]['date'] = $value;
                    }

                }

                foreach ($insert_data as $key => $value)
                {
                    $this->Orderroom_model->add_batch($value);
                }

            }

            // 添加商品
            $go_batch_data = array();
            $order_goods_status = true;
            if ($arg_post['gids'] && $arg_post['gnums'])
            {
                foreach ($arg_post['gids'] as $index => $gid)
                {
                    $go_batch_data[$index] = array(
                        'sid' => $this->sid,
                        'order_id' => $order_id,
                        'good_id' => $gid,
                        'number' => $arg_post['gnums'][$index],
                    );
                }
            }

            if(!empty($go_batch_data))
            {
                $order_goods_status = $this->Orderhotelgoods_model->add_batch($go_batch_data);
            }


            //保存人数日志信息
            $log_data = array(
                'sid' => $this->sid,
                'order_id' => $order_id,
                'number' => $arg_post['male_number'] + $arg_post['woman_number'] + $arg_post['child_number'],
                'date' => $arg_post['start_date'],
                'add_time' => date('Y-m-d'),
                'action_user' => $this->session->userdata('admin_user_name')
            );
            $number_log = $this->Ordernumberlog_model->add_row($log_data);


            if ($contact_return_status && $hor_check && $order_goods_status)
            {
                $this->User_model->_send_sms($contact_data['phone_num'],'SMS_10820180',array('number'=>$hotel_data['number']));
                $this->success('订单生成成功!', site_url('order/adminhotel/index'), true);
            }
            else
            {
                $this->error('订单生成失败!', site_url('order/adminhotel/add'), true);
            }
        }
        else
        {
            $this->error('订单生成失败!', site_url('order/adminhotel/add'), true);
        }
    }

    /**
     * 独立价格模式-订单添加保存
     */
    public function order_independ_save()
    {

        $arg_post = $this->input->post();

        //订单信息
        $order_data = array(
            'sid' => $this->sid,
            'order_sn' => $this->Orderinfo_model->set_order_sn(),
            'order_type' => 1, //酒店订单
            'cat_type' => 1,  //门市订单
            'order_account' => $arg_post['order_account'],
            'room_account' => $arg_post['room_account'],
            'earnest_account' => $arg_post['order_account']/3,
            'order_status' => 4, // 管理员下单已确认状态
            'pay_status' => 1,   // 未支付
            'add_time' => date('Y-m-d H:i:s', now()),
            'order_note' => $arg_post['order_note'],
            'user_id' =>  $this->session->userdata('admin_user_id'),//用户ID
            'admin_user_id' => $this->session->userdata('admin_user_id'),//管理员ID
        );

        $order_id = $this->Orderinfo_model->add_row($order_data);
        if ($order_id)
        {
            //添加联系人
            $contact_data = array(
                'order_id' => $order_id,
                'name' => $arg_post['contact_name'],
                'phone_num' => $arg_post['contact_phone_num'],
                'wx_nick' => $arg_post['wx_nick'],
            );
            $contact_return_status = $this->Ordercontacts_model->add_row($contact_data);


            // 添加酒店订单信息

            $hotel_data = array(
                'sid' => $this->sid,
                'order_id' => $order_id,
                'start_date' => $arg_post['start_date'],
                'end_date' => $arg_post['end_date'],
                'number' => $arg_post['male_number'] + $arg_post['woman_number']+ $arg_post['child_number'],
                'male_number' => $arg_post['male_number'],
                'woman_number' => $arg_post['woman_number'],
                'child_number' => $arg_post['child_number'],
                'room_account' => $arg_post['room_account']
            );

            $hor_check = $this->Orderhotel_model->add_row($hotel_data);



            // 添加房间
            if (!empty($arg_post['room_id']) && is_array($arg_post['room_id'])
                && !empty($arg_post['pricemarket']) && is_array($arg_post['pricemarket']))
            {

                $pricemarket = array_values(array_filter($arg_post['pricemarket']));


                $this->Orderroom_model->delete_row(array('order_id' => $order_id));
                $insert_data = array();
                $range = fomate_range_date($arg_post['start_date'], $arg_post['end_date']);



                foreach ($arg_post['room_id'] as $key => $item)
                {
                    foreach ($range as $index => $value)
                    {
                        $market_pos =  array_keys($arg_post['room_id'],$item);
                        $price = $this->Hotel_model->_get_number_row(array('id'=>$item),'price');
                        $insert_data[$key][$index]['sid'] = $this->sid;
                        $insert_data[$key][$index]['room_id'] = $item;
                        $insert_data[$key][$index]['order_id'] = $order_id;
                        $insert_data[$key][$index]['date'] = $value;
                        $insert_data[$key][$index]['number'] = $pricemarket[$market_pos[0]];
                        $insert_data[$key][$index]['price'] = $price['price'];

                    }

                }

                foreach ($insert_data as $key => $value)
                {
                    $this->Orderroom_model->add_batch($value);
                }

            }

            // 添加商品
            $go_batch_data = array();
            $order_goods_status = true;
            if ($arg_post['gids'] && $arg_post['gnums'])
            {
                foreach ($arg_post['gids'] as $index => $gid)
                {
                    $go_batch_data[$index] = array(
                        'sid' => $this->sid,
                        'order_id' => $order_id,
                        'good_id' => $gid,
                        'number' => $arg_post['gnums'][$index],
                    );
                }
            }

            if(!empty($go_batch_data))
            {
                $order_goods_status = $this->Orderhotelgoods_model->add_batch($go_batch_data);
            }


            //保存人数日志信息
            /*   $log_res = $this->add_order_number_record($order_id,$arg_post['room_id'],$arg_post['pricemarket'],fomate_range_date($arg_post['start_date'], $arg_post['end_date']));

   */

            if ($contact_return_status && $hor_check && $order_goods_status)
            {
                $this->User_model->_send_sms($contact_data['phone_num'],'SMS_10820180',array('number'=>$hotel_data['number']));
                $this->success('订单生成成功!', site_url('order/adminhotel/index'), true);
            }
            else
            {
                $this->error('订单生成失败!', site_url('order/adminhotel/add'), true);
            }
        }
        else
        {
            $this->error('订单生成失败!', site_url('order/adminhotel/add'), true);
        }

    }

    /**
     * 酒店订单编辑页面
     */
    public function edit()
    {
        $order_id = $this->input->get('id');

        //联系人信息
        $this->data['contact_info'] = $this->Ordercontacts_model->get_row(array('order_id' => $order_id));

        //订单基本信息
        $this->data['order_info'] = $this->Orderinfo_model->get_row(array('order_id' => $order_id));

        $hotel_order_info = $this->Orderhotel_model->get_row(array('order_id' => $order_id));
        $this->data['hotel_order_info'] = $hotel_order_info;


        $start = $this->input->get_post('start') ? ($this->input->get_post('start')) : $hotel_order_info['start_date'];
        $end = $this->input->get_post('end') ? ($this->input->get_post('end')) : $hotel_order_info['end_date'];


        if($start != $hotel_order_info['start_date'] || $end != $hotel_order_info['end_date'])
        {
            $change_check = true ;
        }

        //获取订单房间号
        $order_room = array();
        $order_room_market = array();
        $order_room_list = $this->Orderroom_model->get_room_array("order_id = $order_id", "room_id,number");
        if ($order_room_list)
        {
            foreach ($order_room_list as $index => $item)
            {
                $order_room[$index] = $item['room_id'];
                $order_room_market[$item['room_id']] = $item['number']; // room_id 主键 房间入住人数做键值
            }
        }


        $order_room = array_unique($order_room);
        $this->data['order_room'] = $order_room ;
        $this->data['order_room_market'] = $order_room_market ;

        //房间基本信息
        $room_list = $this->Hotel_model->get_number_list(array('sid' => $this->sid), '1000', 1);
        $locked_data = $this->Orderroom_model->get_locked_room_list($start, $end);
        $this->data['lock_room'] = $locked_data['ids'];
        $this->data['lock_key_date'] = $locked_data['dates'];
        $this->data['room_list'] = $room_list;

        $order_goods_result = $this->Orderhotelgoods_model->get_list(array('order_id' => $order_id));

        //获取订单酒水产品
        $order_drinks = array();


        if ($order_goods_result)
        {
            foreach ($order_goods_result as $index => $item)
            {
                $order_drinks[$item['good_id']] = array(
                    'good_id' => $item['good_id'],
                    'number' => $item['number']
                );
            }
        }

        $this->data['order_drinks'] = $order_drinks;


        //获取订单附加产品
        $order_goods = array();
        if ($order_goods_result)
        {
            foreach ($order_goods_result as $index => $item)
            {
                $order_goods[$item['good_id']] = array(
                    'good_id' => $item['good_id'],
                    'number' => $item['number']
                );
            }
        }

        $this->data['order_goods'] = $order_goods;


        if(DEBUG)
        {
            print_r( $this->data['order_goods']);

        }
        $this->data['member_list']  = $this->User_model->get_member_list("sid = " . $this->sid,100,1);

        $this->data['goods_list'] =  $this->Hotel_model->get_extend_product_list("sid = " . $this->sid." and type = 0");


        $this->data['drinks_list'] =  $this->Hotel_model->get_extend_product_list("sid = " . $this->sid." and type = 1");

        //订单支付日志
        $this->data['pay_log'] = $this->Orderpaylog_model->get_list(array('order_id' => $order_id));


        //订单操作日志
        $this->data['order_log'] = $this->Orderlog_model->get_list(array('order_id' => $order_id));


        $order_room_account = $this->Ordernumberlog_model->calc_order_room_account($order_id,$hotel_order_info['start_date'], $hotel_order_info['end_date'], $hotel_order_info['number']);

        $this->data['numbers_log'] = $this->Ordernumberlog_model->get_list(array('order_id' => $order_id));
        $this->data['form_url'] = site_url('order/adminhotel/edit_save');
        $this->data['index_url'] = site_url('order/adminhotel/index');
        $this->data['current_url'] = site_url('order/adminhotel/edit?id=' . $order_id);
        $this->data['order_room_account'] = $order_room_account;
        $this->data['start'] = $start;
        $this->data['days'] = (strtotime($end) - strtotime($start)) / 24 / 60 / 60;
        $this->data['end'] = $end;

        $conflict_orders = $this->Orderroom_model->get_conflict_orders($order_id, $order_room, $start, $end);
        $this->data['conflict_orders'] = $conflict_orders;
        $this->data['change_check'] = $change_check;

        if(intval($this->data['sell_model']) == 1)
        {
            $this->data['form_url'] = site_url('order/adminhotel/edit_independ_save');

//           if(TADMIN)
//          {
              $this->load->view('admin/hotel/independ/edit_main', $this->data);
//          }else
//          {
//              $this->load->view('admin/hotel/tadmin/edit_main', $this->data);
//          }


        }
        elseif (intval($this->data['sell_model']) == 2)
        {



                $period_unit_price = 0 ;
                $date_range = fomate_range_date($start, $end);
                if($date_range)
                {
                    foreach ($date_range as $index => $item)
                    {
                        $period_unit_price += $this->period_price_array[date('w',strtotime($item))];
                    }
                }
                $this->data['period_unit_price'] = $period_unit_price; // 周期单价



            $this->data['form_url'] = site_url('order/adminhotel/edit_mix_save');

            $this->load->view('admin/hotel/mix/edit_main', $this->data);
        }
        else
        {

           /* if(TADMIN)
            {
                $this->load->view('admin/hotel/test/edit_main', $this->data);
            }else
            {
                $this->load->view('admin/hotel/general/edit_main', $this->data);
            }*/

            $this->load->view('admin/hotel/normal/edit_main', $this->data);
        }


    }


    /**
     * 一口价模式-订单编辑保存
     */
    public function edit_save()
    {
        $arg_post = $this->input->post();
        $order_id = $arg_post['order_id'];

        if ($order_id)
        {


            $conflict_rooms = $this->Orderroom_model->get_conflict_rooms($order_id,$arg_post['room_id'],$arg_post['start_date'], $arg_post['end_date']);

            if(!empty($conflict_rooms))
            {
                $this->error('当前订单离店日期与其他订单行程冲突 !', '', true);
            }



            // 修改房间信息
            if (!empty($arg_post['room_id']) && is_array($arg_post['room_id']))
            {

                $this->Orderroom_model->delete_row(array('order_id' => $order_id));
                $insert_data = array();
                $range = fomate_range_date($arg_post['start_date'], $arg_post['end_date']);


                foreach ($arg_post['room_id'] as $key => $item)
                {
                    foreach ($range as $index => $value)
                    {
                        $insert_data[$key][$index]['sid'] = $this->sid;
                        $insert_data[$key][$index]['room_id'] = $item;
                        $insert_data[$key][$index]['order_id'] = $order_id;
                        $insert_data[$key][$index]['date'] = $value;
                    }

                }

                foreach ($insert_data as $key => $value)
                {
                    $this->Orderroom_model->add_batch($value);
                }

            }





            // 更新订单商品
            $goods_data = array();
            if (!empty($arg_post['gids']) && !empty($arg_post['gnums']))
            {
                foreach ($arg_post['gids'] as $index => $gid)
                {
                    $goods_data[] = array(
                        'sid' => $this->sid,
                        'good_id' => $gid,
                        'order_id' => $order_id,
                        'number' => $arg_post['gnums'][$index]
                    );
                }
            }

            $gres = true;
            if(!empty($goods_data))
            {

                $this->Orderhotelgoods_model->delete_row(array('order_id'=>$order_id));
                $gres = $this->Orderhotelgoods_model->add_batch($goods_data);
            }




            //更新联系人信息
            $contact_data = array(
                'name' => $arg_post['contact_name'],
                'phone_num' => $arg_post['contact_phone_num'],
                'wx_nick' => $arg_post['wx_nick'],
            );

            $cres = $this->Ordercontacts_model->edit_row($contact_data, array('order_id' => $order_id));

            //更新酒店订单信息
            $hotel_data = array(
                'number' => $arg_post['woman_number']+  $arg_post['male_number'] + $arg_post['child_number'],
                'woman_number' => $arg_post['woman_number'],
                'male_number' => $arg_post['male_number'],
                'child_number' => $arg_post['child_number'],
                'start_date' => $arg_post['start_date'],
                'end_date' => $arg_post['end_date'],
                'room_account' => $arg_post['room_account']
            );

            $hres = $this->Orderhotel_model->edit_row($hotel_data, array('order_id' => $order_id));


            // 人数变动日志记录

            $nres = $this->Ordernumberlog_model->update_record($order_id, date('Y-m-d') , $arg_post['woman_number']+  $arg_post['male_number']+  $arg_post['child_number']);


            // 入住日期和离店日期变动
//                $this->Ordernumberlog_model->update_record($order_id,$arg_post['start_date'],$arg_post['end_date']);



            $return_url = site_url('order/adminhotel/index');
            if ($arg_post['return_url'])  $return_url = $arg_post['return_url'];

            $ores = $this->edit_order_status($order_id,$arg_post);
            if ($gres&&$ores&&$cres&&$hres)
            {
                $this->success('订单编辑成功!', $return_url, true);
            }
            else
            {
                $this->error('订单编辑失败!', site_url('order/adminhotel/edit?id=' . $order_id), true);
            }
        }
        else
        {
            $this->error('订单编辑失败!', site_url('order/adminhotel/edit?id=' . $order_id), true);
        }
    }


    /**
     * 独立价格模式-订单编辑保存
     */
    public function edit_independ_save()
    {

        $arg_post = $this->input->post();
        $order_id = $arg_post['order_id'];

        if ($order_id)
        {
            $conflict_rooms = $this->Orderroom_model->get_conflict_rooms($order_id,$arg_post['room_id'],$arg_post['start_date'], $arg_post['end_date']);

            if(!empty($conflict_rooms))
            {
                $this->error('当前订单离店日期与其他订单行程冲突 !', '', true);
            }

            // 人数变动日志记录

            $lres = $this->update_order_number_record($order_id,$arg_post['room_id'],$arg_post['pricemarket'],fomate_range_date($arg_post['start_date'], $arg_post['end_date']));


            // 更新房间
            if (!empty($arg_post['room_id']) && is_array($arg_post['room_id'])
                && !empty($arg_post['pricemarket']) && is_array($arg_post['pricemarket']))
            {

                $pricemarket = array_values(array_filter($arg_post['pricemarket']));


                $this->Orderroom_model->delete_row(array('order_id' => $order_id));
                $insert_data = array();
                $range = fomate_range_date($arg_post['start_date'], $arg_post['end_date']);

                foreach ($arg_post['room_id'] as $key => $item)
                {
                    foreach ($range as $index => $value)
                    {
                        $market_pos =  array_keys($arg_post['room_id'],$item);
                        $price = $this->Hotel_model->_get_number_row(array('id'=>$item),'price');
                        $insert_data[$key][$index]['sid'] = $this->sid;
                        $insert_data[$key][$index]['room_id'] = $item;
                        $insert_data[$key][$index]['order_id'] = $order_id;
                        $insert_data[$key][$index]['date'] = $value;
                        $insert_data[$key][$index]['number'] = $pricemarket[$market_pos[0]];
                        $insert_data[$key][$index]['price'] = $price['price'];
                    }
                }

                foreach ($insert_data as $key => $value)
                {
                    $this->Orderroom_model->add_batch($value);
                }

            }



            // 更新订单商品

            $goods_data = array();
            if (!empty($arg_post['gids']) && !empty($arg_post['gnums']))
            {
                foreach ($arg_post['gids'] as $index => $gid)
                {
                    $goods_data[] = array(
                        'sid' => $this->sid,
                        'good_id' => $gid,
                        'order_id' => $order_id,
                        'number' => $arg_post['gnums'][$index]
                    );
                }
            }


            $gres = true;
            if(!empty($goods_data))
            {

                $this->Orderhotelgoods_model->delete_row(array('order_id'=>$order_id));
                $gres = $this->Orderhotelgoods_model->add_batch($goods_data);
            }


            //更新联系人信息
            $contact_data = array(
                'name' => $arg_post['contact_name'],
                'phone_num' => $arg_post['contact_phone_num'],
                'wx_nick' => $arg_post['wx_nick'],
            );

            $cres = $this->Ordercontacts_model->edit_row($contact_data, array('order_id' => $order_id));

            //更新酒店订单信息
            $hotel_data = array(
                'number' => $arg_post['woman_number']+  $arg_post['male_number'] + $arg_post['child_number'],
                'woman_number' => $arg_post['woman_number'],
                'male_number' => $arg_post['male_number'],
                'child_number' => $arg_post['child_number'],
                'start_date' => $arg_post['start_date'],
                'end_date' => $arg_post['end_date'],
                'room_account' => $arg_post['room_account']
            );

            $hres = $this->Orderhotel_model->edit_row($hotel_data, array('order_id' => $order_id));


            $return_url = site_url('order/adminhotel/index');
            if ($arg_post['return_url'])  $return_url = $arg_post['return_url'];


            if (!empty($arg_post['room_id']) && is_array($arg_post['room_id'])){
                $arg_post['room_account'] = $this->calc_independ_room_account($order_id,$arg_post['start_date'],$arg_post['end_date']);
            }


            $ores = $this->edit_order_status($order_id, $arg_post);
            if ($gres && $ores && $cres && $hres)
            {
                $this->success('订单编辑成功!', $return_url, true);
            }
            else
            {
                $this->error('订单编辑失败!', site_url('order/adminhotel/edit?id=' . $order_id), true);
            }
        }
        else
        {
            $this->error('订单编辑失败!', site_url('order/adminhotel/edit?id=' . $order_id), true);
        }
    }


    /**
     * 周期模式-订单编辑保存
     */
    public function edit_mix_save()
    {
        $arg_post = $this->input->post();
        $order_id = $arg_post['order_id'];

        if ($order_id)
        {


            $conflict_rooms = $this->Orderroom_model->get_conflict_rooms($order_id,$arg_post['room_id'],$arg_post['start_date'], $arg_post['end_date']);

            if(!empty($conflict_rooms))
            {
                $this->error('当前订单离店日期与其他订单行程冲突 !', '', true);
            }



            // 修改房间信息
            if (!empty($arg_post['room_id']) && is_array($arg_post['room_id']))
            {

                $this->Orderroom_model->delete_row(array('order_id' => $order_id));
                $insert_data = array();
                $range = fomate_range_date($arg_post['start_date'], $arg_post['end_date']);


                foreach ($arg_post['room_id'] as $key => $item)
                {
                    foreach ($range as $index => $value)
                    {
                        $insert_data[$key][$index]['sid'] = $this->sid;
                        $insert_data[$key][$index]['room_id'] = $item;
                        $insert_data[$key][$index]['order_id'] = $order_id;
                        $insert_data[$key][$index]['date'] = $value;
                    }

                }

                foreach ($insert_data as $key => $value)
                {
                    $this->Orderroom_model->add_batch($value);
                }

            }



            // 更新商品信息
            $goods_data = array();
            if (!empty($arg_post['gids']) && !empty($arg_post['gnums']))
            {
                foreach ($arg_post['gids'] as $index => $gid)
                {
                    $goods_data[$index] = array(
                        'sid' => $this->sid,
                        'good_id' => $gid,
                        'order_id' => $order_id,
                        'number' => $arg_post['gnums'][$index]
                    );
                }
            }

            $gres = true;
            if(!empty($goods_data))
            {

                $this->Orderhotelgoods_model->delete_row(array('order_id'=>$order_id));
                $gres = $this->Orderhotelgoods_model->add_batch($goods_data);
            }



            //更新联系人信息
            $contact_data = array(
                'name' => $arg_post['contact_name'],
                'phone_num' => $arg_post['contact_phone_num'],
                'wx_nick' => $arg_post['wx_nick'],
            );

            $cres = $this->Ordercontacts_model->edit_row($contact_data, array('order_id' => $order_id));

            //更新酒店订单信息
            $hotel_data = array(
                'number' => $arg_post['woman_number']+  $arg_post['male_number'] + $arg_post['child_number'],
                'woman_number' => $arg_post['woman_number'],
                'male_number' => $arg_post['male_number'],
                'child_number' => $arg_post['child_number'],
                'start_date' => $arg_post['start_date'],
                'end_date' => $arg_post['end_date'],
                'room_account' => $arg_post['room_account']
            );

            $hres = $this->Orderhotel_model->edit_row($hotel_data, array('order_id' => $order_id));


            // 人数变动日志记录

            $nres = $this->Ordernumberlog_model->update_record($order_id, date('Y-m-d') , $arg_post['woman_number']+  $arg_post['male_number']+  $arg_post['child_number']);




            $return_url = site_url('order/adminhotel/index');
            if ($arg_post['return_url'])  $return_url = $arg_post['return_url'];

            $ores = $this->edit_order_status($order_id,$arg_post);
            if ($gres&&$ores&&$cres&&$hres)
            {
                $this->success('订单编辑成功!', $return_url, true);
            }
            else
            {
                $this->error('订单编辑失败!', site_url('order/adminhotel/edit?id=' . $order_id), true);
            }
        }
        else
        {
            $this->error('订单编辑失败!', site_url('order/adminhotel/edit?id=' . $order_id), true);
        }
    }


    /**
     * 一口价模式--计算房间金额
     *
     */

    public function calc_order_room_account_ajax()
    {
        $order_id = $this->input->get_post('order_id');
        $start = $this->input->get_post('start');
        $end = $this->input->get_post('end');
        $numbers = $this->input->get_post('numbers');
        $account =  $this->Ordernumberlog_model->calc_order_room_account_exclude_today($order_id,$start,$end,$numbers);
        if($account)
        {
            $this->success(json_encode(array('data'=>$account)), 1, true);
        }
        else
        {
            $this->error('订单总额计算失败!', 1, true);
        }

    }


    /**
     * 混合价格模式--计算房间金额
     *
     */

    public function calc_mix_room_account_ajax()
    {
        $order_id = $this->input->get_post('order_id');
        $start = $this->input->get_post('start');
        $end = $this->input->get_post('end');
        $numbers = $this->input->get_post('numbers');
        $account =  $this->Ordernumberlog_model->calc_mix_room_account_exclude_today($order_id,$start,$end,$numbers);
        if($account)
        {
            $this->success(json_encode(array('data'=>$account)), 1, true);
        }
        else
        {
            $this->error('订单总额计算失败!', 1, true);
        }

    }


    /**
     * 独立价格模式-ajax计算房间金额
     * $ignore 忽略今天 已当前操作的房间人数为准
     */

    public function calc_independ_room_account_ajax()
    {
        $order_id = $this->input->get_post('order_id');
        $start = $this->input->get_post('start');
        $end = $this->input->get_post('end');
        $rids = $this->input->get_post('rids');
        $numbers = $this->input->get_post('numbers');


        $range = fomate_range_date($start, $end);
        $first_day = $range[0];

        $rids = array_filter(explode(',',$rids));
        $numbers = array_filter(explode(',',$numbers));


        $post_data = array();
        if($rids && $numbers)
        {
            foreach ($rids as $index => $rid)
            {
                $post_data[$rid] = $numbers[$index];
            }
        }

        // 订单房间
        $pre_array = array();
        $orm_lits = $this->Orderroom_model->get_room_array("order_id = $order_id", "room_id,number,date,price");



        if ($orm_lits)
        {
            foreach ($orm_lits as $index => $item)
            {
                $pre_array[$item['room_id']][$item['date']] = $item;
            }
        }

        if($post_data)
        {
            foreach ($post_data as $index => $item)
            {
                if($pre_array[$index]) // 清洗今天以后的日期房间的数据
                {

                    foreach ($range as $i => $v)
                    {
                        if($pre_array[$index][$v])
                        {
                            $pre_array[$index][$v]['number'] = $item ;
                        }
                        else
                        {
                            $pre_array[$index][$v]['room_id'] = $index ;
                            $pre_array[$index][$v]['number'] = $item ;
                            $pre_array[$index][$v]['date'] = date('Y-m-d');
                            $pre_array[$index][$v]['price'] = $pre_array[$index][$first_day]['price'] ;
                            $pre_array[$index][$v]['number'] = $item ;
                        }
                    }

                }

                if(!$pre_array[$index])  // 添加新增房间的数据
                {
                    $price = $this->Hotel_model->_get_number_row(array('id'=>$index),'price');
                    foreach ($range as $i => $v)
                    {
                            $pre_array[$index][$v]['room_id'] = $index ;
                            $pre_array[$index][$v]['number'] = $item ;
                            $pre_array[$index][$v]['date'] = date('Y-m-d');
                            $pre_array[$index][$v]['price'] = $price['price'] ;
                            $pre_array[$index][$v]['number'] = $item ;

                    }
                }
            }
        }



        //房间人数日志
        $condition = "order_id = $order_id and date between '{$start}' and '{$end}'" ;
        $exists = $this->Ordernumberlog_model->get_list($condition ,'number,room_id,id,date');

        $exist_logs = array();

        if($exists)
        {
            foreach ($exists as $index => $item)
            {
                $exist_logs[$item['room_id']][$item['date']] = $item ;
            }
        }

        // 清洗今天的日志人数
        if($post_data)
        {
            foreach ($post_data as $index => $item)
            {
                if($exist_logs[$index]) // 最新提交的房间人数 如果之前订单房间存在就更新人数
                {
                    $date = date('Y-m-d');
                    $exist_logs[$index][$date]['number'] = $item ;
                }
            }
        }





        if($pre_array)
        {
            $total = 0 ;
            foreach ($pre_array as $index => $item)  // $index 房间ID   $item 数组
            {
                $account = 0 ;
                if($item)
                {
                   foreach ($item as $key=>$value) // $key 日期   $value 数组
                   {

                     /*  if (TADMIN)
                       {*/


                           $hotel_single = $this->Hotel_model->_get_number_row(array('id' => $index), 'is_suite');

                           if ($hotel_single['is_suite'])
                           {
                               $account += $value['price'];
                           }
                           else
                           {
                               $number = $exist_logs[$index][$key]['number'] ? $exist_logs[$index][$key]['number'] : $value['number'];
                               $account += $number * $value['price'];
                           }

/*
                       }
                       else
                       {

                           $number = $exist_logs[$index][$key]['number'] ? $exist_logs[$index][$key]['number'] : $value['number'];

                           $account += $number * $value['price'];
                       }*/


                   }
                }
                $total += $account ;
            }

        }


        if ($total)
        {
            $this->success(json_encode(array('data' => $total)), 1, true);
        }
        else
        {
            $this->error('订单总额计算失败!', 1, true);
        }
    }



    /**
     * 独立价格模式-计算房间金额
     */

    public function calc_independ_room_account($order_id,$start,$end)
    {
        // 订单房间
        $pre_array = array();
        $orm_lits = $this->Orderroom_model->get_room_array("order_id = $order_id", "room_id,number,date,price");

        if ($orm_lits)
        {
            foreach ($orm_lits as $index => $item)
            {
                $pre_array[$item['room_id']][$item['date']] = $item;
            }
        }


        //房间人数日志
        $condition = "order_id = $order_id and date between '{$start}' and '{$end}'" ;
        $exists = $this->Ordernumberlog_model->get_list($condition ,'number,room_id,id,date');

        $exist_logs = array();

        if($exists)
        {
            foreach ($exists as $index => $item)
            {
                $exist_logs[$item['room_id']][$item['date']] = $item ;
            }
        }



        /*
         *
         *
         *
         *
         *
       $pre_array

        Array
        (
       [34] => Array
        (
            [2016-07-10] => Array
                (
                    [room_id] => 34
                    [number] => 2
                    [date] => 2016-07-10
                    [price] => 600.00
                )

        $exist_logs

        Array
        (
            [34] => Array
            (
                [2016-07-05] => Array
                (
                    [number] => 1
                    [room_id] => 34
                    [id] => 313
                    [date] => 2016-07-05
                )

            )
        )*/
        if($pre_array)
        {
            $total = 0 ;
            foreach ($pre_array as $index => $item)  // $index 房间ID   $item 数组
            {
                $account = 0 ;
                if($item)
                {
                    foreach ($item as $key=>$value) // $key 日期   $value 数组
                    {

                       /* if (TADMIN)
                        {*/


                            $hotel_single = $this->Hotel_model->_get_number_row(array('id' => $index), 'is_suite');

                            if ($hotel_single['is_suite'])
                            {
                                $account += $value['price'];
                            }
                            else
                            {
                                $number = $exist_logs[$index][$key]['number'] ? $exist_logs[$index][$key]['number'] : $value['number'];
                                $account += $number * $value['price'];
                            }

/*
                        }
                        else
                        {
                            $number = $exist_logs[$index][$key]['number'] ? $exist_logs[$index][$key]['number'] : $value['number'];
                            $account += $number * $value['price'] ;
                        }*/

                    }
                }
                $total += $account ;
            }

        }


        return $total ;
    }


    /**
     * 一口价模式-编辑订单状态
     */

    public function edit_order_status($order_id = 0,$arg_post = array())
    {
        if($order_id)
        {
            $po_order_status = $arg_post['order_status'];

            //添加备注信息
            $order_row = $this->Orderinfo_model->get_row(array('order_id' => $order_id), 'order_status,order_account,,room_account');



            //修改订单金额
            if ($order_row['order_account'] != $arg_post['order_account'])
            {
                 $arg_post['note'] .= '(订单金额[' . $order_row['order_account'] . ']调整为[' . $arg_post['order_account'] . '])';
            }


            // 后台管理随时都可以取消
            if ($po_order_status == 3)
            {
                $updating_status =3;  // 订单状态改成已取消
            }

            if ($po_order_status == 2 && in_array($order_row['order_status'],array(1)))
            {
                $updating_status = 2; // 订单状态改成已审核
            }

            if ($po_order_status == 4 && in_array($order_row['order_status'],array(2)))
            {
                $updating_status = 4; // 订单状态改成已确认
            }

            if ($po_order_status == 5 && in_array($order_row['order_status'],array(4)))
            {
                $updating_status = 5; // 订单状态改成已入住
            }

            if ($po_order_status == 6 && in_array($order_row['order_status'],array(5)))
            {
                $updating_status = 6; // 订单状态改成已完成
            }


            $data = array('order_id' => $order_id, 'order_status' => $updating_status, 'note' => $arg_post['note']);


            if($po_order_status !== $order_row['order_status'])
            {
                // 更改订单状态和备注
                $res = $this->Orderinfo_model->translate_order_status($data);
            }

            $order_data = array();
            $upo_res = true;
            if ($order_row['order_account'] != $arg_post['order_account'])
            {
                $order_data ['order_account' ] =  $arg_post['order_account'];  //修改订单金额

            }

            if ($order_row['earnest_account'] != $arg_post['earnest_account'])
            {
                $order_data ['earnest_account' ] =  $arg_post['earnest_account']; //修改定金金额
            }


            if ($order_row['room_account'] != $arg_post['room_account'])
            {
                $order_data ['room_account' ] =  $arg_post['room_account']; //修改房间金额
            }


            if ($order_row['user_id'] != $arg_post['user_id'])
            {
                $order_data ['user_id' ] =  $arg_post['user_id']; //修改user_id
            }

            $upo_res = $this->Orderinfo_model->edit_row($order_data, array('order_id' => $order_id));

            $contact_data = $this->Ordercontacts_model->get_row(array('order_id' => $order_id),'phone_num');
            $hotel_order_data = $this->Orderhotel_model->get_row(array('order_id' => $order_id),'start_date');

            // 操作订单已入住 短信通知游客
            if ($res && $updating_status == 5)
            {
                // 通知游客
                $replace = array('sname' => $this->data['company'], 'date' => $hotel_order_data['start_date'],'phone'=>$this->data['notify_num']);
                $this->User_model->_send_sms($contact_data['phone_num'], 'SMS_10860643', $replace);
            }


            // 操作订单已完成 短信通知游客
            if ($res && $updating_status == 6)
            {
                // 通知游客
                $replace = array('sname' => $this->data['company'], 'date' => $hotel_order_data['start_date'],'phone'=>$this->data['notify_num']);
                $this->User_model->_send_sms($contact_data['phone_num'], 'SMS_10860531', $replace);
            }


            // 订单审核通过通知游客支付定金
            if ($res && $updating_status == 2)
            {
                // 通知游客
                $replace = array('sname' => $this->data['company'], 'date' => $hotel_order_data['start_date']);
                $this->User_model->_send_sms($contact_data['phone_num'], 'SMS_10835528', $replace);
            }


            // 取消房间 删除订单所
            if ($upo_res && $updating_status == 3 )
            {
                $this->Orderroom_model->delete_row(array('order_id' => $order_id));
            }

            return true ;
        }


    }




    /**
     * 添加人数变动日志记录
     *
     * array $pricemarket 房间入住人数
     * array $rooms       房间ids
     * array $range_date  日期数组
     * return true/false
     */


    public function add_order_number_record($order_id = 0 ,$room_ids = array(),$pricemarket = array(),$range_date = array())
    {

        if(!$order_id || !$pricemarket || !$room_ids  || !$range_date) return false;

        $pricemarket = array_values(array_filter($pricemarket));

        $add_data = array();
        foreach ($room_ids as $index => $room_id)
        {


            foreach ($range_date as $key => $item)
            {
                $add_data[] = array(
                    'sid' => $this->sid,
                    'order_id' => $order_id,
                    'room_id' => $room_id,
                    'number' => $pricemarket[$index],
                    'date' => $item ,
                    'add_time' => date('Y-m-d'),
                    'action_user' => $this->session->userdata('admin_user_name')
                );
            }

        }

        return $this->Ordernumberlog_model->add_batch($add_data);


    }

    /**
     * 房间人数变动日志记录
     *
     * array $pricemarket 房间入住人数
     * array $rooms       房间ids
     * return true/false
     */


    public function update_order_number_record($order_id = 0 ,$room_ids = array(),$pricemarket = array(),$range_date = array())
    {

        if(!$order_id || !$pricemarket || !$room_ids ) return false;


        $pricemarket = array_values(array_filter($pricemarket));

        $date = date('Y-m-d');
        $rooms = $this->Orderroom_model->get_room_array(array('order_id'=>$order_id,'date'=>"'{$date}'"));
        $order_room = array(); // 订单存储房间入住人数
        if($rooms)
        {
           foreach ($rooms as $index => $item)
           {
               $order_room[$item['room_id']] = $item['number'];
           }
        }


        // 已经存储的日志
        $exists = $this->Ordernumberlog_model->get_list(array('order_id'=>$order_id,'date'=>"'{$date}'"),'number,room_id,id');
        if($exists)
        {
            foreach ($exists as $index => $item)
            {
                $exist_logs[$item['room_id']] = $item ;
            }
        }

        $post_data = array();  // 订单提交房间入住人数
        if($pricemarket && $room_ids)
        {

            foreach ($room_ids as $index => $room_id)
            {
                $post_data[$room_id] = $pricemarket[$index];
            }
        }



        if($post_data && $order_room)
        {


            foreach ($post_data as $index => $item)
            {
                if($item != $order_room[$index]) // 提交过来的房间人数 与之前订单房间人数不一直
                {

                    if($exist_logs[$index]) // 如果日志有这条记录就更新数据
                    {

                        $update_data = array(
                            'number' => $item,
                            'add_time' => date('Y-m-d'),
                            'action_user' => $this->session->userdata('admin_user_name')
                        );
                        $this->Ordernumberlog_model->edit_row($update_data,array('id' => $exist_logs[$index]['id'])) ;
                    }
                    else                // 如果日志没有这条记录就添加数据
                    {
                        $add_data = array(
                            'sid' => $this->sid,
                            'order_id' => $order_id,
                            'room_id' => $index,
                            'number' => $item,
                            'date' => date('Y-m-d') ,
                            'add_time' => date('Y-m-d'),
                            'action_user' => $this->session->userdata('admin_user_name')
                        );
                        $this->Ordernumberlog_model->add_row($add_data);
                    }

                }
            }
        }
        return true;
    }



    /**
     * 删除订单
     *
     * @param   POST 表单数据
     * return true/false
     */

    public function delete_order()
    {

        $id = $this->input->get('id');
        if (empty($id))
        {
            $post_id = $this->input->post('id');
            $res = $this->Orderinfo_model->remove_row("order_id in ($post_id)");
        }
        else
        {
            $res = $this->Orderinfo_model->remove_row(array('order_id' => $id)); // 删除订单基础表
            $this->Orderroom_model->delete_row(array('order_id' => $id)); // 删除房间库存表
            $this->Ordercontacts_model->remove_row(array('order_id' => $id)); // 删除订单联系人表
            $this->Orderhotel_model->remove_row(array('order_id' => $id));  // 删除酒店订单表
        }

        if ($res)
        {
            $this->success('操作成功', site_url('order/adminhotel/index'), true);
        }
        else
        {
            $this->error('操作失败', '', true);
        }
    }

    /**
     * 检测房间冲突
     * return true/false
     */

    public function check_orders_conflict()
    {
        $order_id = $this->input->get_post('order_id');
        $rooms = $this->input->get_post('rooms');
        $start = $this->input->get_post('start');
        $end =   $this->input->get_post('end');

        $room_array = explode(',',$rooms);

        $return = $this->Orderroom_model->get_conflict_orders($order_id,$room_array,$start,$end);

        if(!empty($return))
        {
            $this->error('当前离店日期与其他订单行程冲突 !', '', true);
        }
        $this->success('success', '', true);
    }


    /**
     * 房间库存
     * return true/false
     */
    public function room_repertory()
    {
        $start = $this->input->get_post('start') ? $this->input->get_post('start') : date('Y-m-d');
        $end = $this->input->get_post('end') ? $this->input->get_post('end') : date('Y-m-d',strtotime('+1 day'));



        $this->data['room_list'] = $this->Hotel_model->get_number_array(array('sid' => $this->sid));
        $locked_data = $this->Orderroom_model->get_locked_room_list($start, $end);




        $this->data['lock_room'] = $locked_data['ids'];
        $this->data['lock_key_date'] = $locked_data['dates'];
        $this->data['start'] = $start;
        $this->data['end'] = $end;


//        if(TADMIN)
//        {
           /* foreach ($this->data['room_list'] as $key=>$value)
            {

            }*/


            foreach ($this->data['room_list'] as $key => $value)
            {
                $order_contacts_res  =array();
                if(in_array($value['id'],$locked_data['ids']))
                {
                    $condition = "sid = $this->sid and room_id = {$value['id']} and date between '{$start}' and '{$end}' ";
                    $order_ids_res = $this->Orderroom_model->get_room_array($condition, 'order_id');
                    if ($order_ids_res)
                    {
                        $order_ids = array();

                        foreach ($order_ids_res as $index => $order_ids_re)
                        {
                            $order_ids[$index] = $order_ids_re['order_id'];
                        }
                    }
                    $where = "order_id in (" . implode(array_unique($order_ids), ',') . ")";
                    $order_contacts_res = $this->Ordercontacts_model->get_rows($where, 'name,phone_num');
                }

                $this->data['room_list'][$key]['contact_list'] = $order_contacts_res ;
            }


//            print_r($this->data['room_list']);
//        }



        $this->data['export_url'] = site_url('order/adminhotel/index?ajax=1&start='.$start.'&end='.$end);



        $this->load->view('admin/hotel/repertory_list',$this->data);
    }
}
